package edu.pku.sei.mte.modification.command;

import edu.pku.sei.mte.mtemodel.metamodel.RTypeReference;
import edu.pku.sei.mte.mtemodel.model.MReference;

public class AddingEdgeCommand extends ModelModificationCommand {
	
	private MReference newEdge;

	public MReference getNewEdge() {
		return newEdge;
	}

	public void setNewEdge(MReference newEdge) {
		this.newEdge = newEdge;
	}

	@Override
	public void execute() throws Exception {
		if(!getModel().getNodes().contains(newEdge.getSource()))
			addNodeRequest(getModel(), newEdge.getSource(), getContext());
		if(!getModel().getNodes().contains(newEdge.getTarget()))
			addNodeRequest(getModel(), newEdge.getTarget(), getContext());
		if(basicAddEdge(newEdge))
			commit();
	}

	@Override
	public void undo() {
		basicRemoveEdge(newEdge);
	}

	@Override
	public boolean isViolated() {
		boolean flag = false;
		for(RTypeReference type : getModel().getTypeGraph().getEdges()){
			if(type.equals(newEdge.getType())){
				flag = true;
				break;
			}
		}
		if(!flag)
			return true;
		if(!newEdge.getSource().getType().isA(newEdge.getType().getSource()))
			return true;
		if(!newEdge.getTarget().getType().isA(newEdge.getType().getTarget()))
			return true;
		return super.isViolated();
	}
	
}